//
//  BWNetworkTool.swift
//  weibo
//
//  Created by libowen on 16/5/22.
//  Copyright © 2016年 libowen. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethods: Int {
    case POST
    case GET
}
struct API {
    static let hostName = "https://api.weibo.com/"
    static let loadAccessToken = "oauth2/access_token"
    static let loadUserInfo = "2/users/show.json"
    static let loadHomedata = "2/statuses/home_timeline.json"
}
class BWNetworkTool: AFHTTPSessionManager {
    static let sharedTools: BWNetworkTool = {
        let url = NSURL(string: API.hostName)
        let tools = BWNetworkTool(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    func request(method: HTTPMethods,urlString: String, parameters: AnyObject?,finished: (responseObject: AnyObject?, error: NSError?) -> () ) {
        let success = {(task: NSURLSessionDataTask,result: AnyObject?) -> () in
           finished(responseObject: result, error: nil)
        }
        let failure = {(task: NSURLSessionDataTask?,error: NSError) -> () in
           finished(responseObject: nil, error: error)
        }
        
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
extension BWNetworkTool {
    func loadAccessToken(code: String,finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        let parameters = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        request(.POST, urlString: API.loadAccessToken, parameters: parameters, finished: finished)
    }
    func loadUserInfo(response: [String : AnyObject], finished:(responseObject: AnyObject?, error: NSError?) -> ()) {
        let token = response["access_token"]!
        let uid = response["uid"]!
    
        let parameters = ["access_token": token, "uid": uid]
        request(.GET, urlString: API.loadUserInfo, parameters: parameters, finished: finished)

    }
}

extension BWNetworkTool {
    func loadHomePageData(finished: (reponseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = BWUserAccountModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        let parameters = ["access_token" : token]
        request(.GET, urlString: API.loadHomedata, parameters: parameters, finished: finished)
    }
}






















